package com.df.happylearn.messages;

import com.android.volley.VolleyError;
import com.df.happylearn.model.MessageInfo;
import com.df.happylearn.model.MessageRead;
import com.df.happylearn.request.DataProvider;
import com.df.happylearn.sqlite.DBUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dingfeng on 2016/5/25.
 */
public class MessagesPresenter implements MessagesContract.Presenter {

    private final MessagesContract.View mMessagesView;
    private static int LIMIT = 10;
    private int page = 1;
    private List<MessageRead> readList = new ArrayList<>();
    private List<Integer> readIds = new ArrayList<>();

    public MessagesPresenter(MessagesContract.View messagesView) {
        mMessagesView = messagesView;
        mMessagesView.setPresenter(this);
    }

    @Override
    public void start() {
        loadMessages(true);
    }

    @Override
    public void loadMessages(final boolean isFirst) {
        if (isFirst) {
            page = 1;
        }
        DataProvider.getInstance().getMessage(0, page, LIMIT, "0", new DataProvider.Callback<ArrayList<MessageInfo>>() {
            @Override
            public void onSuccess(ArrayList<MessageInfo> data) {
                mMessagesView.showMessages(data, isFirst);
                page++;
            }

            @Override
            public void onError(VolleyError error) {
                if (isFirst) {
                    mMessagesView.showNoMessages();
                }
            }
        }, false);
    }

    @Override
    public void getReadedIds() {
        readList = DBUtil.getInstance().getMessageReadDao().queryAll();
        if (readList != null) {
            for (MessageRead item : readList) {
                readIds.add(item.mId);
            }
        } else {
            readList = new ArrayList<>();
        }
        mMessagesView.setReadIds(readIds);
    }

    @Override
    public void updateReadState(int messageId) {
        MessageRead messageRead = new MessageRead();
        messageRead.mId = messageId;
        DBUtil.getInstance().getMessageReadDao().saveOrUpdate(messageRead);
        mMessagesView.addReadId(messageId);
    }
}
